const express = require('express')
let app = express()
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const session = require('express-session')
const md5 = require('md5-node')
const multiparty = require('multiparty')
const fs = require('fs')
const mongoose = require('mongoose')
const ObjectId = mongoose.Schema.ObjectId

app.set('view engine', 'ejs')
app.set('views', 'templates')
app.use('/static', express.static('static'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(cookieParser('yoonasy'))
app.use(session({secret: 'yoonasy123', resave: false, rolling: true, saveUninitialized: true, cookie: { maxAge: 30 * 6e4 }}))


mongoose.connect('mongodb://127.0.0.1:27017/product', { useNewUrlParser: true })
const uploadFolder = 'static/public'

const userSchema = new mongoose.Schema({
    user: String,
    password: String,
    status: Boolean
})
const productSchema = new mongoose.Schema({
    title: String,
    price: Number,
    fee: Number,
    pic: String,
    description: String
})
const userModal = mongoose.model('users', userSchema) // mongoose表必须以s结尾
const productModel = mongoose.model('products', productSchema) // mongoose表必须以s结尾


function createFolder(folder) {
    try {
        fs.accessSync(folder)
    } catch (e) {
        fs.mkdir(folder)
    }
}
createFolder(uploadFolder)

// 自定义中间件 判断登录权限
app.use((req, res, next) => {
    if (!(session.userInfo && session.userInfo.user)) {
        if (!(req.url === '/login' || req.url === "/doLogin" || req.url === '/logout')) {
            res.redirect('/login')
            return // 重定向之后 执行next会报错 所以return
        }
    } else if (req.url === '/login' || req.url === '/doLogin') {
        res.redirect('/product')
        return // 重定向之后 执行next会报错 所以return
    }
    next()
})

app.get('/', (req, res) => {
    res.send('hello nodejs')
})
// 登录
app.get('/login', (req, res) => {
    req.session.destroy(err => {
        if (err) {
            throw err
        } else {
            res.render('login')
        }
    })
})
// 注销
app.get('/logout', (req, res) => {
    session.userInfo = {}
    res.redirect('/login')
})
// 登录处理
app.all('/doLogin', (req, res) => {
    let user = req.body.user
    let password = md5(req.body.password)
    userModal.find({ user, password }, (err, data) => {
        if (data.length) {
            // 登录成功
            session.userInfo = data[0]
            // 只要登录之后就需要重新设置全局ejs
            // ejs 设置全局数据  所有模板都能使用  注意默认全局有：hostname uptime freemem totalmem cpus type release networkInterfaces homedir userInfo
            app.locals.userinfo = session.userInfo || {}
            res.redirect('/product')
        } else {
            res.send("<script>alert('账号或密码错误');location.href='/login'</script>")
        }
    })
    // 注册
    // userModal(req.body).save(function (err, data) {
    //     if (err) throw err
    //     res.render('login')
    // })
})
// 商品列表
app.get('/product', (req, res) => {
    productModel.find({}, (err, data) => {
        if (err) {
            throw err
        }
        res.render('product', {data})
    })
})
// 商品添加
app.all('/productadd', (req, res) => {
    if (req.method === 'POST') {
        let form = new multiparty.Form()
        form.uploadDir = uploadFolder // 目录必须存在才能上传

        form.parse(req, (err, fields, files) => {
            if (err) throw err
            let pic = files.pic.length ? files.pic[0].path : ''
            let json = { pic }
            let fieldsArr = ['title', 'price', 'fee', 'description']
            fieldsArr.forEach(e => {
                let field = fields[e]
                if (field.length) field = field[0]
                json[e] = field
            })
            productModel(json).save((err, data) => {
                if (err) {
                    throw err
                } else {
                    res.redirect('/product') // 上传成功到数据库
                    return 0
                }
            })
        })
    } else {
        res.render('productAdd')
    }
})
// 商品编辑显示
app.get('/productedit/:_id', (req, res) => {
    let _id = req.params._id
    productModel.find({ _id }, (err, data) => {
        if (err) {
            console.log(err)
            res.render('productedit')
        } else {
            res.render('productedit', { data: data[0] })
        }
    })
})
// 商品编辑修改数据
app.all('/doProductEdit', (req, res) => {
    if (req.method === 'POST') {
        let form = new multiparty.Form()
        form.uploadDir = uploadFolder // 目录必须存在才能上传

        form.parse(req, (err, fields, files) => {
            if (err) throw err
            let json = {}
            console.log(files.pic)
            if (files.pic[0].originalFilename) {
                json.pic = files.pic[0].path
            } else {
                fs.unlink(__dirname + '/' + files.pic[0].path) // 删除临时上传的图片文件
            }
            let fieldsArr = ['title', 'price', 'fee', 'description']
            fieldsArr.forEach(e => {
                let field = fields[e]
                if (field.length) field = field[0]
                json[e] = field
            })
            productModel.updateOne({_id: fields._id}, {$set: json}, (err, data) => {
                if (err) {
                    throw err
                } else {
                    res.redirect('/product') // 上传成功到数据库
                    return 0
                }
            })
        })
    }
})

// 商品删除
app.all('/productdelete/:_id', (req, res) => {
    let _id = req.params._id
    productModel.find({_id}).remove((err, data) => {
        res.redirect('/product')
    })
})


app.listen(3000, '0.0.0.0')
